package com.example.grab_the_order;

import android.accessibilityservice.AccessibilityService;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import android.view.accessibility.AccessibilityNodeInfo;
import android.widget.EditText;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class GrabOrderAccessibilityService extends AccessibilityService {

    private static final String TAG = "MyAccessibilityService";
    public static final String ACTION_ORDER_DETECTED = "com.example.grab_the_order.ORDER_DETECTED";
    public static final String EXTRA_ORDER_DATA = "order_data";

    private final WeChatTester weChatTester = new WeChatTester(this);
    private static GrabOrderAccessibilityService sInstance;

    // =================================================================================
    // 【微信/通用聊天测试模块】
    // =================================================================================
    private static class WeChatTester {
        private final String TAG = "GenericChatTester";
        private final Handler mHandler = new Handler(Looper.getMainLooper());
        private boolean isTestRunning = false;
        private final Context mContext;

        public WeChatTester(Context context) {
            this.mContext = context;
        }

        public void handleEvent(AccessibilityNodeInfo rootNode) {
            if (isTestRunning) return;

            AccessibilityNodeInfo editText = findFirstEditableEditText(rootNode);
            if (editText != null) {
                Log.d(TAG, "在当前页面找到一个可编辑的输入框，准备开始测试...");
                isTestRunning = true;
                startTestLoop();
            }
        }

        private AccessibilityNodeInfo findFirstEditableEditText(AccessibilityNodeInfo parentNode) {
            if (parentNode == null) return null;
            for (int i = 0; i < parentNode.getChildCount(); i++) {
                AccessibilityNodeInfo childNode = parentNode.getChild(i);
                if (childNode == null) continue;
                if (childNode.getClassName() != null && childNode.getClassName().equals(EditText.class.getName()) && childNode.isEditable()) {
                    return childNode;
                }
                AccessibilityNodeInfo editTextInChild = findFirstEditableEditText(childNode);
                if (editTextInChild != null) {
                    return editTextInChild;
                }
            }
            return null;
        }

        private void startTestLoop() {
            final String text1 = "0987654321";
            final String text2 = "1234567890";

            Runnable testRunnable = new Runnable() {
                int step = 0;
                @Override
                public void run() {
                    if (!isTestRunning) return;

                    AccessibilityNodeInfo freshRoot = sInstance.getRootInActiveWindow();
                    if (freshRoot == null) { stopTest(); return; }
                    AccessibilityNodeInfo freshEditText = findFirstEditableEditText(freshRoot);
                    if (freshEditText == null) { stopTest(); return; }

                    switch (step) {
                        case 0: pasteText(freshEditText, text1); break;
                        case 1: pasteText(freshEditText, ""); break;
                        case 2: pasteText(freshEditText, text2); break;
                        case 3: pasteText(freshEditText, ""); break;
                    }
                    step = (step + 1) % 4;
                    freshRoot.recycle();
                    mHandler.postDelayed(this, 2000);
                }
            };
            mHandler.post(testRunnable);
        }

        public void stopTest() {
            if (isTestRunning) {
                Log.d(TAG, "停止通用聊天测试。");
                mHandler.removeCallbacksAndMessages(null);
                isTestRunning = false;
            }
        }

        private void pasteText(AccessibilityNodeInfo node, String text) {
            ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE);
            if (clipboard == null) return;
            ClipData clip = ClipData.newPlainText("text", text);
            clipboard.setPrimaryClip(clip);
            node.performAction(AccessibilityNodeInfo.ACTION_FOCUS);
            node.performAction(AccessibilityNodeInfo.ACTION_PASTE);
        }
    }
    // =================================================================================

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        sInstance = this;
        String packageName = event.getPackageName() != null ? event.getPackageName().toString() : "";
        AccessibilityNodeInfo rootNode = getRootInActiveWindow();
        if (rootNode == null) return;

        switch (packageName) {
            case "com.didichuxing.driver":
            case "com.sankuai.meituan.dispatch.home":
                weChatTester.stopTest();
                handleGrabOrderEvent(rootNode, packageName);
                break;
            case "com.tencent.mm":
                weChatTester.handleEvent(rootNode);
                break;
            default:
                weChatTester.stopTest();
                break;
        }
        rootNode.recycle();
    }

    private void handleGrabOrderEvent(AccessibilityNodeInfo rootNode, String packageName) {
        Map<String, Object> orderData = parseOrderInfo(rootNode, packageName);
        if (orderData != null && !orderData.isEmpty()) {
            Log.d(TAG, "解析到抢单App订单数据: " + orderData.toString());
            sendOrderDataBroadcast(orderData);
            findAndClickButtonByText(rootNode, "立即抢单");
        }
    }
    
    // (其他核心方法保持不变)
    private void sendOrderDataBroadcast(Map<String, Object> orderData) {
        Intent intent = new Intent(ACTION_ORDER_DETECTED);
        intent.putExtra(EXTRA_ORDER_DATA, (Serializable) orderData);
        sendBroadcast(intent);
        Log.d(TAG, "已发送订单数据广播。");
    }

    private void findAndClickButtonByText(AccessibilityNodeInfo rootNode, String text) {
        if (rootNode == null || text == null) return;
        List<AccessibilityNodeInfo> nodes = rootNode.findAccessibilityNodeInfosByText(text);
        if (nodes != null && !nodes.isEmpty()) {
            for (AccessibilityNodeInfo node : nodes) {
                AccessibilityNodeInfo clickableParent = getClickableParent(node);
                if (clickableParent != null) {
                    Log.d(TAG, "发现目标按钮，准备点击: " + text);
                    clickableParent.performAction(AccessibilityNodeInfo.ACTION_CLICK);
                    clickableParent.recycle();
                    return;
                }
            }
        }
    }

    private AccessibilityNodeInfo getClickableParent(AccessibilityNodeInfo node) {
        AccessibilityNodeInfo parent = node;
        while (parent != null) {
            if (parent.isClickable()) {
                return parent;
            }
            parent = parent.getParent();
        }
        return null;
    }

    private Map<String, Object> parseOrderInfo(AccessibilityNodeInfo rootNode, String packageName) {
        HashMap<String, Object> orderInfo = new HashMap<>();
        if (packageName.equals("com.didichuxing.driver")) {
            orderInfo.put("amount", 35.5);
            orderInfo.put("distance", 7.2);
        }
        if (orderInfo.containsKey("amount")) {
            return orderInfo;
        }
        return null;
    }

    @Override
    public void onInterrupt() {
        Log.e(TAG, "服务被中断");
        weChatTester.stopTest();
    }

    @Override
    protected void onServiceConnected() {
        super.onServiceConnected();
        sInstance = this;
        Log.d(TAG, "无障碍服务已连接");
    }

    @Override
    public void onDestroy() {
        weChatTester.stopTest();
        sInstance = null;
        super.onDestroy();
    }
}